<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>点名程序</title>
    <style>
        table {
            border-collapse: collapse;
            margin: 0 auto;
        }

        td {
            border: 1px solid #000;
            width: 80px;
            height: 80px;
            text-align: center;
            line-height: 50px;
            background-color: yellow;
        }
    </style>
</head>

<body>
<table id="studentTable"></table>
<button id="startButton">开始点名</button>

<script>
    class RollCall {
        constructor() {
            this.studentCount = 20;
            this.studentTable = document.getElementById('studentTable');
            this.cells = [];
            this.studentsPerRow = 8;
            this.intervalId = null;
            this.selectedCell = null;
            this.startButton = document.getElementById('startButton');
            this.startButton.addEventListener('click', this.start.bind(this));
        }

        init() {
            let rowCount = Math.ceil(this.studentCount / this.studentsPerRow);
            for (let i = 0; i < rowCount; i++) {
                let row = this.studentTable.insertRow();
                for (let j = 0; j < this.studentsPerRow && i * this.studentsPerRow + j < this.studentCount; j++) {
                    let cell = row.insertCell();
                    cell.textContent = `学生${i * this.studentsPerRow + j + 1}`;
                    this.cells.push(cell);
                }
            }
        }

        start() {
            if (this.intervalId) return; // 如果正在运行则不重复启动
            this.init(); // 重新初始化状态
            let currentIndex = 0;
            this.intervalId = setInterval(() => {
                if (this.selectedCell) {
                    this.selectedCell.style.backgroundColor = 'yellow';
                }
                this.cells[currentIndex].style.backgroundColor = 'lightblue';
                setTimeout(() => {
                    this.cells[currentIndex].style.backgroundColor = 'yellow';
                }, 200);
                currentIndex = (currentIndex + 1) % this.studentCount;
            }, 200);

            setTimeout(() => {
                clearInterval(this.intervalId);
                this.intervalId = null;
                const randomIndex = Math.floor(Math.random() * this.studentCount);
                this.selectedCell = this.cells[randomIndex];
                this.selectedCell.style.backgroundColor = 'red';
                alert(`点到：${this.selectedCell.textContent}`);
            }, 5000);
        }
    }

    const rollCall = new RollCall();
    rollCall.init();
</script>
</body>

</html>